package id.net.iconpln.bb.client.view;

import id.net.iconpln.bb.client.model.Stock;
import id.net.iconpln.bb.client.service.PortRPCService;
import id.net.iconpln.bb.client.service.PortRPCServiceAsync;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.form.MultiField;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.TimeField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbPortPencatatan extends LayoutContainer {
	private final PortRPCServiceAsync service = GWT.create(PortRPCService.class);
	private FormBinding formBindings;  
	private FormData formData; 
	private ListStore storeKplBongkar,storeKplAntri, storeJetty,storeKplCatatan;
	private Grid gridKplBongkar, gridKplAntri,gridKplCatatan;
	private ComboBox cboJetty;
	private DateField tglTa, time_bongkarD,time_CatatanD,time_selesaiD;
	private TextField<String> ash_kirim,cv_kirim,ts_kirim,tm_kirim,no_bongkar;
	private TimeField time_bongkarT,time_CatatanT,time_selesaiT;
	private MultiField multiSelesai;
	private Button bSelesaiBongkar;
	
	
	  @Override  
	  protected void onRender(Element parent, int index) {  
	    super.onRender(parent, index);  
	    setLayout(new FitLayout());
	    initStore();
	    
	    formData = new FormData("-20"); 
	    ContentPanel cp = new ContentPanel();  
	   
	    cp.setHeaderVisible(false);
	    cp.setFrame(true);  
	    cp.setSize(900, 400);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL)); 
	  
	    gridKplCatatan = createGridCatatan();  
	    gridKplCatatan.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);  
	    gridKplCatatan.getSelectionModel().addListener(Events.SelectionChange,  
	        new Listener<SelectionChangedEvent<BaseModel>>() {  
	          public void handleEvent(SelectionChangedEvent<BaseModel> be) {  
	            if (be.getSelection().size() > 0) {  	              
	              formBindings.bind((ModelData) be.getSelection().get(0));  
	            } else {  
	              formBindings.unbind();  
	            }  
	          }  
	        });
	    
	    
	    gridKplBongkar = createGridBongkar();
	    gridKplBongkar.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);  
	    gridKplBongkar.getSelectionModel().addListener(Events.SelectionChange,  
	        new Listener<SelectionChangedEvent<Stock>>() {  
	          public void handleEvent(SelectionChangedEvent<Stock> be) {  
	            if (be.getSelection().size() > 0) {  
	              formBindings.bind((ModelData) be.getSelection().get(0));  
	            } else {  
	              formBindings.unbind();  
	            }  
	          }  
	        });
	    ToolBar tbPltu = new ToolBar();
	    tbPltu.add(new LabelToolItem("<b>Data kapal Bongkar</b>"));
	    tbPltu.add(new SeparatorToolItem());
	    bSelesaiBongkar = new Button("Selesai Bongkar");
	    bSelesaiBongkar.setIcon(IconHelper.createStyle("icon-clock"));
//	    tbPltu.add(bSelesaiBongkar);
	    bSelesaiBongkar.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub

					MessageBox.alert("Info","Pilih Data Vessel / Tongkang", null);
				
			}
	    		
		});
	    	
		
	    

	    	    
	    ToolBar tbCatatan = new ToolBar();
	    tbCatatan.add(new LabelToolItem("<b>Pencatatan Bongkar Harian</b>"));
	    tbCatatan.add(new SeparatorToolItem());
	    
	    FormPanel panel = createForm(); 
	    panel.setScrollMode(Scroll.AUTO);
	    formBindings = new FormBinding(panel, true);  
  
	    
	    
	    ContentPanel pkirim = new ContentPanel();
	    pkirim.setHeaderVisible(false);
	    pkirim.setLayout(new FitLayout());
	    pkirim.add(gridKplBongkar);
	    pkirim.setTopComponent(tbPltu);
	    
	    aktivitasDermaga("antri","BONGKAR","", "");
//	    aktivitasDermaga("antri","REC_BONGKAR","", "");
	    
	    ContentPanel pKplCatatan = new ContentPanel();
	    pKplCatatan.setHeaderVisible(false);
	    pKplCatatan.setLayout(new RowLayout(Orientation.HORIZONTAL));
	    pKplCatatan.add(gridKplCatatan,new RowData(1, 1));
	    pKplCatatan.setTopComponent(tbCatatan);

	    ContentPanel pKplBongkar = new ContentPanel();
	    pKplBongkar.setHeaderVisible(false);
	    pKplBongkar.setLayout(new RowLayout(Orientation.HORIZONTAL));
	    pKplBongkar.add(gridKplBongkar,new RowData(1, 1));
	    pKplBongkar.setTopComponent(tbPltu);

	    
	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);
	    p.setLayout(new RowLayout(Orientation.VERTICAL));
	    p.add(pKplBongkar, new RowData(.99, .5));
	    p.add(pKplCatatan, new RowData(.99, .5));
	    
	    
	    cp.add(panel, new RowData(.4, 1));
	    cp.add(p, new RowData(.6, 1));
	    
	   
	    add(cp, new FitData(5));  
	  }  
	  private void initStore(){
		  storeKplBongkar = new ListStore(); 
		  storeKplCatatan = new ListStore(); 
	  }

	  private Grid createGridBongkar() {  
		  
		    List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

		    ColumnConfig column = new ColumnConfig();	    	     

		    column = new ColumnConfig();  
		    column.setId("no_bongkar");  
		    column.setHeader("No Bongkar");  
		    column.setWidth(150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig();  
		    column.setId("pemasok");  
		    column.setHeader("Pemasok");  
		    column.setWidth(150);  
		    configs.add(column); 

		    
		    column = new ColumnConfig();  
		    column.setId("nama_transport");  
		    column.setHeader("Nama kapal");    
		    column.setWidth(150);    
		    configs.add(column);  

		    column = new ColumnConfig();  
		    column.setId("no_pengiriman");  
		    column.setHeader("No Pengiriman");  
		    column.setWidth(100);  
		    configs.add(column);  	
		    
		    column = new ColumnConfig();  
		    column.setId("id_bongkar");  
		    column.setHidden(true);
		    column.setHeader("id_bongkar");  
		    column.setWidth(100);  
		    configs.add(column);  	
		    
		    column = new ColumnConfig();  
		    column.setId("kode_jetty");  
		    column.setHeader("Jetty");  
		    column.setWidth(100);  
		    configs.add(column);  	  
		    
		    column = new ColumnConfig();  
		    column.setId("time_bongkar");  
		    column.setHeader("Mulai Bongkar");  
		    column.setDateTimeFormat(DateTimeFormat.getFormat("dd/MM/yyyy hh.mm"));
		    column.setWidth(150);  
		    configs.add(column);  

		    
		    storeKplBongkar.setMonitorChanges(true);  

		  
		    ColumnModel cm = new ColumnModel(configs);  
	  
	    gridKplBongkar = new Grid(storeKplBongkar, cm);  
	    gridKplBongkar.getView().setEmptyText("Data Empty");
	    gridKplBongkar.setLoadMask(true);  
	    gridKplBongkar.mask("load Data ...","x-mask-loading");
	    gridKplBongkar.setBorders(false);  
//	    grid.setAutoExpandColumn("pemasok");  
	    gridKplBongkar.setBorders(true);  
	    gridKplBongkar.addListener(Events.CellClick, new Listener<BaseEvent>() {            
        public void handleEvent(BaseEvent ge) {
        	try{
        		gridKplCatatan.mask("load Data ...","x-mask-loading");
        		Map mapParam = new FastMap();
        		mapParam.put("id_pltu", Registry.get("idPltu").toString());
        		mapParam.put("id_bongkar", gridKplBongkar.getSelectionModel().getSelectedItem().get("id_bongkar").toString());
        		GWT.log("id bongkar " + gridKplBongkar.getSelectionModel().getSelectedItem().get("id_bongkar").toString() + " id _pltu " + Registry.get("idPltu").toString());
  			   service.getListDermagaBy("REC_BONGKAR", mapParam,new AsyncCallback<List<Map>>() {
  		  			public void onFailure(Throwable caught) {
  		  				GWT.log(caught.getMessage(), null);
  		  			}
  		  			public void onSuccess(List<Map> result) {
  		  			    	storeKplCatatan.removeAll();
  		  			    	storeKplCatatan.add(ClientModule.setListBaseModelFromListMap(result));
  		  			    	gridKplCatatan.unmask();
  		  			
  		  			   
  		  			}
  		  		});
        		
        	}catch (Exception e) {
					// TODO: handle exception
        		e.getMessage();
				}

         	
        }
		});

	    return gridKplBongkar;  
	  }   
	 
 
	  
	  private FormPanel createForm() {  
	    FormPanel panel = new FormPanel();	    
	    panel.setHeaderVisible(false);
	    
	    FieldSet fieldSet = new FieldSet();  
	    fieldSet.setHeading("Pencatatan Bongkar");  
	    fieldSet.setCollapsible(false);
	    
	  
	    FormLayout layout = new FormLayout();  
	    layout.setLabelWidth(150);  
	    fieldSet.setLayout(layout);  

	    no_bongkar = new TextField<String>();  
	    no_bongkar.setName("no_bongkar");  
	    no_bongkar.setFieldLabel("No Bongkar");   
	    no_bongkar.setReadOnly(true);
	    fieldSet.add(no_bongkar, formData);	  	  
	    
	    TextField<String> no_pengiriman = new TextField<String>();  
	    no_pengiriman.setName("no_pengiriman");  
	    no_pengiriman.setFieldLabel("No Pengiriman");   
	    no_pengiriman.setReadOnly(true);
	    fieldSet.add(no_pengiriman, formData);	  	  
	    
	    final TextField<String> id_bongkar = new TextField<String>();  
	    id_bongkar.setName("id_bongkar");  
	    id_bongkar.setVisible(false);
	    id_bongkar.setFieldLabel("id_bongkar");    
	    fieldSet.add(id_bongkar, formData);	  	  
	    
	    final TextField<String> alat_bongkar = new TextField<String>();	    
	    alat_bongkar.setName("alat_bongkar"); 
	    alat_bongkar.setReadOnly(true);
	    alat_bongkar.setFieldLabel("Alat Bongkar");    
	    fieldSet.add(alat_bongkar, formData);
	    
	    	
	    TextField<String> nama_transport = new TextField<String>();
	    nama_transport.setName("nama_transport");  
	    nama_transport.setReadOnly(true);
	    nama_transport.setFieldLabel("Nama Kpl / Tongkang");	    
	    fieldSet.add(nama_transport, formData);
	    
	    TextField<String> kode_jetty = new TextField<String>();
	    kode_jetty.setName("kode_jetty");
	    kode_jetty.setReadOnly(true);
	    kode_jetty.setFieldLabel("Jetty");	
	    
	    fieldSet.add(kode_jetty, formData);
	    
	    MultiField multiCatatan = new MultiField();
	    multiCatatan.setFieldLabel("Tanggal / Jam");
	    multiCatatan.setSpacing(10);
	
		time_CatatanD = new DateField();
		time_CatatanD.setWidth(90);
		time_CatatanD.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
  
		time_CatatanT = new TimeField();
		time_CatatanT.setWidth(90);
		
		multiCatatan.add(time_CatatanD);
		multiCatatan.add(time_CatatanT);
	    
		fieldSet.add(multiCatatan, formData);

	    multiSelesai = new MultiField();
	    multiSelesai.setFieldLabel("Selesai Bongkar");
	    multiSelesai.setSpacing(10);
	    multiSelesai.setVisible(false);
	
		time_selesaiD = new DateField();
		time_selesaiD.setWidth(90);
		time_selesaiD.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
  
		time_selesaiT = new TimeField();
		time_selesaiT.setWidth(90);
		
		multiSelesai.add(time_selesaiD);
		multiSelesai.add(time_selesaiT);
	    
		fieldSet.add(multiSelesai, formData);

		
		final TextField<String> volume = new TextField<String>();
	    volume.setName("volume");  
	    volume.setFieldLabel("Volume");	    
	    fieldSet.add(volume, formData);

	    final TextArea keterangan = new TextArea();
	    keterangan.setName("keterangan");  
	    keterangan.setFieldLabel("Keterangan");	    
	    fieldSet.add(keterangan, formData);

	    
	    panel.add(fieldSet);  	     
	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);	    
	    p.setButtonAlign(HorizontalAlignment.RIGHT);  
	    p.addButton(new Button("Reset", new SelectionListener<ButtonEvent>() {  
	      @Override  
	      public void componentSelected(ButtonEvent ce) {  

	      }  
	    }));  
	    p.addButton(new Button("Submit", new SelectionListener<ButtonEvent>() {  
	      @Override  
	      public void componentSelected(ButtonEvent ce) {
	    	  
	    	  MessageBox.confirm("Info", "Apakah Anda Yakin Ingin Menyimpan Data?",new Listener<MessageBoxEvent>() {

					@Override
					public void handleEvent(MessageBoxEvent be) {
						// TODO Auto-generated method stub
						Button btn = be.getButtonClicked();
						if (btn.getText().equals("Yes")){

					    	   Map mapParam = new FastMap();
					    	   
					            mapParam.put("record_time", time_CatatanD.getRawValue() + " "+ time_CatatanT.getRawValue());
					    		mapParam.put("tanggal", time_CatatanD.getRawValue());
					    		mapParam.put("no_bongkar", no_bongkar.getValue());
					    		mapParam.put("id_bongkar", id_bongkar.getValue());
					    		mapParam.put("volume", volume.getValue());
					    		mapParam.put("keterangan", keterangan.getRawValue().toString());
					    	    mapParam.put("id_pltu", Registry.get("idPltu").toString());
					    		mapParam.put("createby", Registry.get("whoAmI").toString());
					    		mapParam.put("app_access", "WEB");
				   			    mapParam.put("crud", "CREATE");
				//
					    		
					    		Set set = mapParam.entrySet(); 
					    		Iterator i = set.iterator(); 
					    		while(i.hasNext()) { 
					    		Map.Entry me = (Map.Entry)i.next();
				//	    			MessageBox.alert(me.getKey()+"",": " + me.getValue(), null);
						    		GWT.log(me.getKey() + ": " + me.getValue()); 
					    		} 
				
					    		service.insertDermagaBb("REC_BONGKAR", mapParam,new AsyncCallback<List<Map>>() {
					    			public void onFailure(Throwable caught) {
					    				GWT.log(caught.getMessage(), null);
					    			}
				
					    			public void onSuccess(List<Map> result) {	    				
					    				Info.display("debug ","notification code " + result );	    					    				
					    				gridKplCatatan.mask("load Data ....","x-mask-loading");
				
					    				  Map mapParams = new FastMap();
					    				  mapParams.put("id_bongkar", id_bongkar.getValue());
					    				  mapParams.put("id_pltu", Registry.get("idPltu").toString());
					    				  service.getListDermagaBy("REC_BONGKAR", mapParams,new AsyncCallback<List<Map>>() {
					    			  			public void onFailure(Throwable caught) {
					    			  				GWT.log(caught.getMessage(), null);
					    			  			}
					    			  			public void onSuccess(List<Map> result) {
					    			  			    	storeKplCatatan.removeAll();
					    			  			    	storeKplCatatan.add(ClientModule.setListBaseModelFromListMap(result));
					    			  			    	gridKplCatatan.unmask();
					    			  			}
					    			  		});
					    				MessageBox.alert("Informasi", " " + result + "id bongkar : " +id_bongkar.getValue() , null);
					    			}
					    		});
						    }	
						}
					});
	      }  
	    }));  

	    panel.add(p);
	    
	    return panel;  
	  }  
	  private Grid createGridCatatan() {  
		  
		    List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

		    ColumnConfig column = new ColumnConfig();	    	     
		    
		    column = new ColumnConfig();  
		    column.setId("record_time");
//		    column.setDateTimeFormat(DateTimeFormat.get);  
		    column.setHeader("tanggal / jam");  
		    column.setWidth(150);  
		    configs.add(column); 

		    
		    column = new ColumnConfig();  
		    column.setId("volume");  
		    column.setHeader("Volume");    
		    column.setWidth(150);    
		    configs.add(column);  

		    column = new ColumnConfig();  
		    column.setId("keterangan");  
		    column.setHeader("Keterangan");  
		    column.setWidth(100);  
		    configs.add(column);  	
		    

		    storeKplCatatan.setMonitorChanges(true);  
		  
		    ColumnModel cm = new ColumnModel(configs);  
	  
	    gridKplCatatan = new Grid(storeKplCatatan, cm);  
	    gridKplCatatan.getView().setEmptyText("Data Empty");
	    gridKplCatatan.setLoadMask(true);  
//	    gridKplCatatan.mask("load Data ...","x-m	ask-loading");
	    gridKplCatatan.setBorders(false);  
//	    grid.setAutoExpandColumn("pemasok");  
	    gridKplCatatan.setBorders(true);  
	    gridKplCatatan.addListener(Events.CellClick, new Listener<BaseEvent>() {            
        public void handleEvent(BaseEvent ge) {
        	try{

//        		String tgl_td = gridKplCatatan.getSelectionModel().getSelectedItem().get("tgl_td");
//        		String norakor = gridKplAntri.getSelectionModel().getSelectedItem().get("kode_jetty").toString();
//            	SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy"); 
//            	Date tgl = dateFormat.parse(test);
//        		String mulai_Catatan = gridKplCatatan.getSelectionModel().getSelectedItem().get("time_merapat");
        		time_CatatanT.setRawValue("00.00");

            	
        	}catch (Exception e) {
					// TODO: handle exception
        		e.getMessage();
				}

         	
        }
		});

	    return gridKplCatatan;  
	  }   

	  private void aktivitasDermaga(String module, final String codectrl , String put1,String param1){
		  Map mapParam = new FastMap();
		  mapParam.put("id_pltu", Registry.get("idPltu").toString());
		  
			  service.getListDermagaBy(codectrl, mapParam,new AsyncCallback<List<Map>>() {
		  			public void onFailure(Throwable caught) {
		  				GWT.log(caught.getMessage(), null);
		  			}
		  			public void onSuccess(List<Map> result) {
//		  			     if (codectrl.equals("REC_BONGKAR")){
//		  			    	storeKplCatatan.removeAll();
//		  			    	storeKplCatatan.add(ClientModule.setListBaseModelFromListMap(result));
//		  			    	gridKplCatatan.unmask();
//		  			     }else if(codectrl.equals("BONGKAR")){
			  			    	storeKplBongkar.removeAll();
			  			    	storeKplBongkar.add(ClientModule.setListBaseModelFromListMap(result));
			  			    	gridKplBongkar.unmask();
		  			    	 
//		  			     }
		  			   
		  			}
		  		});
	  }

}
